import { timeoutTask, showWxToast } from '../../utils/index';
import { getPoolMoney, getZyzInfo, getZyzRank, zyzRecharge, startZyz, sendPrizeInfo, sendBroadCast } from '../../api/zyz/zyz';
import { wxPay } from '../../api/pay';
import defaultContent from '../../assets/constant/default';

const zhufuList = [
    '美酒佳肴,不甚荣幸',
    '醉酒饱德，不胜感激',
    '小小红包,感谢招待',
    '感谢招待,祝愿安康',
];
// 礼物数组
const giftList = [
    {
        id: 1,
        gift: 'rocket1',
        name: '火箭小号',
        imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket1.png',
        isChoosed: true
    }, {
        id: 2,
        gift: 'rocket2',
        name: '火箭中号',
        imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket2.png',
        isChoosed: false
    }, {
        id: 3,
        gift: 'rocket3',
        name: '大号大号',
        imgUrl: 'https://static.hudongmiao.com/joymewMp/zyz/rocket3.png',
        isChoosed: false
    }
];

let tmpInterval = null; //用于倒计时
let tmpInterval2 = null; //用于轮询
let lock = false; //锁，用于确保 倒计时方法 一轮只调用一次
let lock2 = false;//锁，用于确保 执行动画的过程中不可以点按钮
let lock3 = false;//锁，用于确保 开始游戏按钮不能连续点击
Page({
    data: {
        luckyMoney: 0,
        wheelRodateDeg: 0,
        isLuckyShow: false,
        luckyAni: '',
        gameStatus: 1, // 游戏状态(控制页面显示)
        prizeItemList: [],// 奖项列表(带汉字单位)
        prizeItemValList: [],// 奖项数值列表(不带汉字单位) 
        poolMoney: 0, //奖池金额
        countDownNum: 0,// 倒计时
        isEntry: false,// 充值入口
        topRankList: [],// 排行榜列表
        otherRankList: [],
        userId: '',
        openId: '',
        name: '',
        headImg: '',
        turnId: '', //一场游戏的id 0代表要充值 否则代表这场游戏的场id
        giftList: giftList,
    },
    onLoad: function (options) {
        lock = false;
        lock2 = false;
        lock3 = false;
        tmpInterval = null;
        tmpInterval2 = null;
        this.setData({
            userId: options.userId,
            openId: options.openId,
            name: options.name,
            headImg: options.headImg,
            prizeItemList: options.zyzList.split(','),
            prizeItemValList: options.zyzList.replace(/[\u4e00-\u9fa5]/g, '').split(','),

        });
        this.requestPoolMoney();
    },
    onShow: function () {
        this.toGame();
    },
    onHide: function () {
        //清除定时器
        clearInterval(tmpInterval);
        clearInterval(tmpInterval2);
        tmpInterval = null;
        tmpInterval2 = null;
        lock = false;
    },
    onUnload: function () {
        //清除定时器
        clearInterval(tmpInterval);
        clearInterval(tmpInterval2);
        tmpInterval = null;
        tmpInterval2 = null;
    },
    showLucky() {
        this.setData({
            luckyAni: 'showLuckyAni',
            isLuckyShow: true,
        });
        // 4s后消失
        timeoutTask(() => {
            this.setData({
                luckyAni: 'hideLuckyAni',
            });
            timeoutTask(() => {
                this.setData({
                    isLuckyShow: false,
                });
            }, 100);
        }, 4000)
    },
    tapstartNyn() {
        getZyzInfo().then((res) => {
            console.log(res);
            this.setData({
                turnId: res.data.id
            });
            this.startGame();
        }).catch((err) => {
            console.log(err);
            showWxToast('网络异常');
        });
    },
    // 选择礼物
    chooseGift(e) {
        console.log(e)
        const choosedId = e.currentTarget.dataset.id;
        const tmpGiftList = this.data.giftList;
        tmpGiftList.forEach(item => {
            if (item.id === choosedId) {
                item.isChoosed = true;
            } else {
                item.isChoosed = false;
            }
        });
        this.setData({
            giftList: tmpGiftList
        });
    },
    // 转一转动画
    gameAniStart(endMoney) {
        let endIndex = this.findIndexByPrizeItem(endMoney);
        // 转盘当前选中项
        let nowIndex = 0;
        // 圈数(周期)
        let circle = 0;
        //转盘 加速阶段 缓冲阶段(确保<=5)
        //情况1：前三个周期->最后一个周期小于5   ani1 ani2
        //情况2:前三个周期->最后一个周期大于5   ani1 + endIndex-4
        let step1 = setInterval(() => {
            if (nowIndex === 9) {
                nowIndex = 0;
                this.setData({
                    wheelRodateDeg: (nowIndex * 36)
                });
                circle += 1;
            }
            if (circle === 3) {
                // 三圈后判断是否进入缓冲阶段
                if (endIndex < 4) {
                    clearInterval(step1);
                    let step2 = setInterval(() => {
                        if (nowIndex === endIndex) {
                            clearInterval(step2);
                            this.setData({
                                wheelRodateDeg: (nowIndex * 36)
                            });
                            timeoutTask(() => {
                                this.showLucky();
                            }, 500);
                        } else {
                            this.setData({
                                wheelRodateDeg: (nowIndex * 36)
                            })
                            if (nowIndex == 9) {
                                nowIndex = 0;
                            } else {
                                nowIndex += 1;
                            }
                        }
                    }, 500);
                } else {
                    //加速阶段停止位置 endIndex-4
                    if (nowIndex === (endIndex - 4)) {
                        clearInterval(step1);
                        let step2 = setInterval(() => {
                            if (nowIndex === endIndex) {
                                clearInterval(step2);
                                this.setData({
                                    wheelRodateDeg: (nowIndex * 36)
                                })
                                timeoutTask(() => {
                                    this.showLucky();
                                }, 500);
                            } else {
                                this.setData({
                                    wheelRodateDeg: (nowIndex * 36)
                                })
                                if (nowIndex == 9) {
                                    nowIndex = 0;
                                } else {
                                    nowIndex += 1;
                                }
                            }
                        }, 500)
                    } else {
                        this.setData({
                            wheelRodateDeg: (nowIndex * 36)
                        })
                        nowIndex += 1;
                    }
                }
            } else {
                this.setData({
                    wheelRodateDeg: (nowIndex * 36)
                });
                nowIndex += 1;
            }
        }, 100)

    },
    // 充钱玩转一转
    recharge() {
        if (!this.data.isEntry) {
            // 最后十五秒购买入口关闭
            showWxToast('购买入口关闭');
            return;
        }
        if (lock2) {
            return;
        }
        lock2 = true;
        zyzRecharge({
            userId: this.data.userId,
            openId: this.data.openId,
        }).then((res) => {
            console.log(res);
            return wxPay(res);
        }).then(() => {
            showWxToast('礼物发送成功!');
            this.sendGift(this.getChoosedGift());
            // startGame
            timeoutTask(() => {
                console.log('***2s后自动转一转***')
                this.tapstartNyn();
            }, 2000);

        }).catch((err) => {
            console.log(err);
            showWxToast('支付失败!');
            lock2 = false;
        });
    },
    getChoosedGift() {
        return this.data.giftList.find(item => {
            return item.isChoosed;
        });
    },
    sendGift(giftChoosed) {
        let tmpCode = '';
        if (giftChoosed.id == 1) {
            tmpCode = 5002;
        } else if (giftChoosed.id == 2) {
            tmpCode = 6002;
        } else if (giftChoosed.id == 3) {
            tmpCode = 7002;
        }
        const c = JSON.stringify({
            code: tmpCode,
            param: {
                headImg: this.data.headImg,
                nickname: this.data.name,
                wish: zhufuList[parseInt(Math.random() * 3)]
            }
        });
        sendBroadCast({
            c,
        });
    },
    // 转一转
    startGame() {
        startZyz({
            turnId: this.data.turnId,
        }).then((res) => {
            console.log('startNyn result:', res);
            //res.data.desc 奖项；endMoney中奖的金额；totalMoney 奖池金额
            //奖池金额刷新
            if (res.data.totalMoney.remainCoin) {
                this.setData({
                    poolMoney: res.data.totalMoney.remainCoin
                })
            }
            this.setData({
                luckyMoney: res.data.endMoney,
            });
            //游戏动画开始
            this.gameAniStart(res.data.endMoney);

            // 4s动画停止后发送广播(必须要中奖的情况)
            if (parseInt(res.data.endMoney) > 0) {
                timeoutTask(() => {
                    this.sendBroad(res.data.endMoney, res.data.totalMoney.balance);
                }, 4000);
            }
            timeoutTask(() => {
                lock2 = false;
            }, 4000);
        }).catch((err) => {
            console.log(err);
            lock2 = false;
        });
    },
    // 点击进入游戏
    toGame() {
        if (lock3) {
            return;
        }
        lock3 = true;
        this.requestGameInitInfo();
    },
    // 获取奖池金额
    requestPoolMoney() {
        getPoolMoney().then((res) => {
            console.log(res);
            this.setData({
                poolMoney: res.data.balance
            });
        }).catch((err) => {
            console.log(err);
        });
    },
    // 获取游戏相关信息
    requestGameInitInfo() {
        getZyzInfo().then((res) => {
            console.log('***获取转一转基本信息***');
            console.log(res);
            //res.data.id 发送礼物 1转一转
            if (res.data.id == 0) {
                this.setData({
                    turnId: res.data.id
                })
            } else {
                this.setData({
                    turnId: res.data.id
                })
            }
            // 时间处理(用于倒计时) res.data.endTime
            if (res.data.endTime === '0') {
                // 游戏未开始的情况处理
                showWxToast('游戏尚未开始!');
            } else {
                let countTime = this.timeHandle(res.data.endTime);
                console.log('***接口返回endTime***');
                console.log(res.data.endTime);
                this.countDown(countTime);
                this.setData({
                    gameStatus: 2,
                });
                // 轮询获取充值和中奖列表
                if (!tmpInterval2) {
                    tmpInterval2 = setInterval(() => {
                        this.requestTipList();
                    }, 4000);
                }
            }
            lock3 = false;
        }).catch((err) => {
            console.log(err);
            lock3 = false;
        });
    },
    timeHandle(endTime) {
        //获取当前时间戳
        var nowTime = (new Date()).getTime();
        var subTime = parseInt((parseInt(endTime) - parseInt(nowTime)) / 1000);
        if (subTime < 0) {
            subTime = 0;
        }
        return subTime;
    },
    countDown(second) {
        if (lock == false && !tmpInterval) {
            lock = true;
            tmpInterval = setInterval(() => {
                if (second <= 1) {
                    this.setData({
                        isEntry: false,
                        countDownNum: second
                    })
                    this.requestRankList();
                } else {
                    second -= 1;
                    if (second <= 15) {
                        this.setData({
                            isEntry: false
                        })
                    } else {
                        this.setData({
                            isEntry: true
                        })
                    }
                    this.setData({
                        countDownNum: second
                    })
                }
            }, 1000)
        }
    },
    // 获取排行榜列表
    requestRankList() {
        getZyzRank().then((res) => {
            console.log(res);
            lock = false;
            let tmpTopRankArray = [];
            let tmpOtherRankArray = [];
            let count = 0;
            let tmpLen = res.data.list.length;
            // 限制中奖名单人数最多不超过10个
            if (tmpLen > 10) {
                tmpLen = 10;
            }
            while (count < tmpLen) {
                if (count < 3) {
                    tmpTopRankArray.push({
                        nickname: res.data.list[count].wx_name,
                        headimgurl: res.data.list[count].avator,
                        money: Math.floor(parseFloat(res.data.list[count].money))
                    });
                } else {
                    tmpOtherRankArray.push({
                        num: count < 0 ? `0${count + 1}` : (count + 1),
                        nickname: res.data.list[count].nickname,
                        headimgurl: res.data.list[count].headimgurl,
                        money: Math.floor(parseFloat(res.data.list[count].money))
                    });
                }
                count += 1;
            }
            if (tmpTopRankArray.length < 3) {
                const tmpLen2 = tmpTopRankArray.length;
                for (let i = tmpLen2; i < 3; i += 1) {
                    tmpTopRankArray.push({
                        nickname: 'Player',
                        headimgurl: defaultContent.defaultHeadImg,
                        money: 0,
                    });
                }
            }
            // 不足七个补齐
            if (tmpOtherRankArray.length < 7) {
                const tmpLen3 = tmpOtherRankArray.length;
                for (let i = tmpLen3; i < 7; i += 1) {
                    tmpOtherRankArray.push({
                        num: i + 3 < 0 ? `0${i + 4}` : (i + 4),
                        nickname: 'Player',
                        headimgurl: defaultContent.defaultHeadImg,
                        money: 0,
                    });
                }
            }

            console.log(tmpOtherRankArray);
            this.setData({
                topRankList: tmpTopRankArray,
                otherRankList: tmpOtherRankArray,
                gameStatus: 3,
            });
            // 停止轮询
            clearInterval(tmpInterval2);
            clearInterval(tmpInterval);
            tmpInterval = null;
            tmpInterval2 = null;
        }).catch((err) => {
            console.log(err);
        });
    },
    // 发广播
    sendBroad(golds, remainCoins) {
        sendPrizeInfo({
            gold: golds,
            remainCoin: remainCoins,
            turnId: this.data.turnId,
        }).then((res) => {
            console.log(res);
        }).catch((err) => {
            console.log(err);
            showWxToast('网络异常');
        });
    },
    // 根据奖项查找下标
    findIndexByPrizeItem(prizeItem) {
        let tmpLen = this.data.prizeItemValList.length;
        let tmpArr = this.data.prizeItemValList;
        let tmpIndex = -1;
        for (let i = 0; i < tmpLen; i += 1) {
            if (tmpArr[i] === prizeItem) {
                tmpIndex = i;
                break;
            }
        }
        return tmpIndex;
    },
    // 获取充值和中奖列表
    requestTipList() {
        getPoolMoney().then((res) => {
            console.log(res);
            const subTime = this.timeHandle(res.data.endTime);
            if (subTime <= 0) {
                // 游戏提前结束
                this.requestRankList();
            }
            this.setData({
                poolMoney: res.data.balance,
            })
        }).catch((err) => {
            console.log(err);
        })
    },
    toAgreement: function () {
        wx.navigateTo({
            url: '/pages/agreement/agreement'
        });
    },
});